package com.app.asktom;


import java.util.ArrayList;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.app.asktom.abs.AbsActivity;
import com.app.asktom.abs.AbsHttpAsync;
import com.app.asktom.component.Config;
import com.app.asktom.component.DeviceHelper;
import com.app.asktom.component.HttpHelper;
import com.app.asktom.component.JsonHelper;
import com.app.asktom.component.LazyAdapter;
import com.app.asktom.component.LazyAdapterExt;
import com.app.asktom.model.User;



public class ViewFoodActivity extends AbsActivity {

    ListView list;
    LazyAdapterExt adapter;
	String[] pic;
	String[] picName;
	String[] thumbsUp;
	String[] thumbsDown;
	String[] picId;
    String[] uploaderNum;
    String[] coordinates;
    
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.loading);
	    /*ActionBar actionBar = getActionBar();
	    actionBar.setDisplayHomeAsUpEnabled(false);*/
		
		// Show the Up button in the action bar.
//		getActionBar().setDisplayHomeAsUpEnabled(true);
		
		User user = new User(this);
		if(!user.isSendFriendsNumberAlreadySend()) {
			SendFriendNumberTask friendNumberTask = 
					new SendFriendNumberTask();
			friendNumberTask.setActivity(this);
			friendNumberTask.execute(Config.getInstance().get("baseUrl"));
		}
		
		
		ViewFoodTask viewFoodTask = new ViewFoodTask();
		viewFoodTask.setActivity(this);
		viewFoodTask.execute(Config.getInstance().get("baseUrl"));
		
//		list=(ListView)findViewById(R.id.list);
//        adapter=new LazyAdapter(this, mStrings);
//        adapter.imageLoader.clearCache();
//        list.setAdapter(adapter);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		ViewFoodTask viewFoodTask = new ViewFoodTask();
		viewFoodTask.setActivity(this);
		viewFoodTask.execute(Config.getInstance().get("baseUrl"));		
	}
	
	@Override
	protected void onDestroy() {
		/*list.setAdapter(null);*/
		super.onDestroy();
	}
	
//    public OnClickListener listener=new OnClickListener(){
//        @Override
//        public void onClick(View arg0) {
//            adapter.imageLoader.clearCache();
//            adapter.notifyDataSetChanged();
//        }
//    };	

	public void search(View view) {
		SearchFoodTask searchFoodTask = new SearchFoodTask();
		searchFoodTask.setActivity(this);
		searchFoodTask.setShowLoading(true);
		searchFoodTask.execute(Config.getInstance().get("baseUrl"));
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_view_food, menu);
		return true;
	}

	public void upload(View view) {
		Intent intent = new Intent(this,UploadActivity.class);
		startActivity(intent);
	}
	
	@SuppressLint("ShowToast")
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch(item.getItemId()) {
//			case R.id.menu_quit:
//				this.finish();
//				return true;
//			case R.id.upload:
//				Intent intent = new Intent(this,UploadActivity.class);
//				startActivity(intent);
//				return true;
//			case R.id.search:
//				intent = new Intent(this,SearchActivity.class);
//				startActivity(intent);
//				return true;
			default:
				return super.onOptionsItemSelected(item);
		}		
		
//		case android.R.id.home:
//			// This ID represents the Home or Up button. In the case of this
//			// activity, the Up button is shown. Use NavUtils to allow users
//			// to navigate up one level in the application structure. For
//			// more details, see the Navigation pattern on Android Design:
//			//
//			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//			//
//			NavUtils.navigateUpFromSameTask(this);
//			return true;
//		}
//		return super.onOptionsItemSelected(item);
	}
	
	private class SearchFoodTask extends AbsHttpAsync {

		@Override
		protected void onPostExecute(String result) {
//			Intent intent = new Intent(this.activity,MapActivity.class);
//			this.activity.startActivity(intent);
//			return null;
			String stat = "";
			Log.d("DEBUG", this.response);
			
			ArrayList<Map<String,String>> arrList = 
					JsonHelper.getInstance()
					.responseSearchFood(this.response);
			
			if(this.response.startsWith("{")) {
				stat = arrList.get(0).get("stat");
				Toast.makeText(this.activity, arrList.get(0).get("msg"),
						Toast.LENGTH_LONG).show();					
			} else {
				Intent intent = new Intent(this.activity,MapActivity.class);
				intent.putExtra("response", this.response);
				this.activity.startActivity(intent);
			}
			
			super.onPostExecute(result);
		}
		
		@Override
		protected String doInBackground(String... params) {
			User user = new User(this.activity);
			Map<String, String> map = user.getUserInfo();
			HttpHelper httpHelper = new HttpHelper();
			httpHelper.setPost(true);
			httpHelper.setUrl(params[0]);
			httpHelper.setPostParam("appId", "WBTOM");
			httpHelper.setPostParam("req", "VIEW");
			httpHelper.setPostParam("user", map.get("phoneNumber"));
			httpHelper.setPostParam("pass", map.get("password"));
//			httpHelper.setPostParam("coord", "");
//			httpHelper.setPostParam("add", "");
			httpHelper.setPostParam("categ", "FOOD");
//			httpHelper.setPostParam("establishment", "");
			httpHelper.setPostParam("name", this.getTextValue(R.id.txtSearchFoodname));
//			httpHelper.setPostParam("tags", "");
//			httpHelper.setPostParam("userget", "");
			httpHelper.setPostParam("meter", "");
			httpHelper.sendRequest();
			this.setResponse(httpHelper.getResponse());
			
			return this.getResponse();
			
			

		}
		
	}
	
	private class ViewFoodTask extends AbsHttpAsync {
		@Override
		protected void onPostExecute(String result) {
			String stat = "";
			if(this.getResponse() != null &&
					!this.getResponse().startsWith("error:")) {
//				int start = this.getResponse().indexOf("{");
//				int end = this.getResponse().length();
//				this.response = this.response.substring(start,end);
			
				Log.d("DEBUG","RESPONSE: " + this.response);
				
				ArrayList<Map<String,String>> arrList = 
						JsonHelper.getInstance()
						.responseViewFood(this.response);
		
				if(this.response.startsWith("{")) {
					stat = arrList.get(0).get("stat");
					Toast.makeText(this.activity, arrList.get(0).get("msg"),
							Toast.LENGTH_LONG).show();					
				}
				Log.d("DEBUG", arrList.size() + "===== SIZE");
				
				pic = new String[arrList.size()];
				picName = new String[arrList.size()];
				thumbsUp = new String[arrList.size()];
				thumbsDown = new String[arrList.size()];
				picId = new String[arrList.size()];
				uploaderNum = new String[arrList.size()];
				coordinates = new String[arrList.size()];
				for(int i = 0; i < arrList.size(); i++) {
					pic[i] = arrList.get(i).get("S3picloc");
					picName[i] = arrList.get(i).get("S3name");
					thumbsUp[i] = arrList.get(i).get("S3total");
//					thumbsDown[i] = arrList.get(i).get("S3meter");
					picId[i] = arrList.get(i).get("S3id");
					uploaderNum[i] = arrList.get(i).get("UFfriendunedited");
					coordinates[i] = arrList.get(i).get("S3coordFull");
					Log.d("DEBUG", "PIC: " + pic[i]);
				}
				
				if(!stat.equals("NG")) {
					
					this.activity.setContentView(R.layout.activity_view_food);
					list=(ListView)findViewById(R.id.list);
			        adapter = new LazyAdapterExt(this.activity, 
			        		pic, picName, thumbsUp, picId);
//			        adapter.imageLoader.clearCache();
			        list.setAdapter(adapter);		

			        list.setOnItemClickListener(new OnItemClickListener() {

						@Override
						public void onItemClick(AdapterView<?> arg0, View arg1,
								int position, long arg3) {
							Intent intent = new Intent(activity,ViewDetailActivity.class);
							intent.putExtra("id", picId[position]);
							intent.putExtra("url", pic[position]);
							intent.putExtra("picName", picName[position]);
							intent.putExtra("uploaderNum", uploaderNum[position]);
							intent.putExtra("coords", coordinates[position]);
							activity.startActivity(intent);
						}
			        });
				}		
			}
			super.onPostExecute(result);
		}
		
		@Override
		protected String doInBackground(String... params) {
			User user = new User(this.activity);
			Map<String, String> map = user.getUserInfo();
			HttpHelper httpHelper = new HttpHelper();
			httpHelper.setPost(true);
			httpHelper.setUrl(params[0]);
			httpHelper.setPostParam("appId", "WBTOM");
			httpHelper.setPostParam("req", "VIEW");
			httpHelper.setPostParam("user", map.get("phoneNumber"));
			httpHelper.setPostParam("pass", map.get("password"));
			httpHelper.setPostParam("sqloffset", "0");
			httpHelper.setPostParam("sqllimit", "20");
			httpHelper.setPostParam("categ", "FOOD");
			httpHelper.sendRequest();
			this.setResponse(httpHelper.getResponse());
			
			return this.getResponse();
		}
				
	}

	private class SendFriendNumberTask extends AbsHttpAsync {

		@Override
		protected void onPostExecute(String result) {
			Log.d("DEBUG","friend response:" + this.response);
			if(this.getResponse() != null &&
					!this.getResponse().startsWith("error:")) {
				
				int start = this.getResponse().indexOf("{");
				int end = this.getResponse().length();
				this.response = this.response.substring(start,end);
				
				Map<String,String> map = JsonHelper.getInstance()
						.reponseSendFriends(this.response);
				if(!map.isEmpty()) {
					User user = new User(activity);
					user.updateUserSetSendFriendNumber();
					Toast.makeText(this.activity, map.get("msg"),
							Toast.LENGTH_LONG).show();
				}
			}
			super.onPostExecute(result);
		}
		
		@Override
		protected String doInBackground(String... params) {
			User user = new User(this.activity);
			Map<String, String> map = user.getUserInfo();
			HttpHelper httpHelper = new HttpHelper();
			httpHelper.setPost(true);
			httpHelper.setUrl(params[0]);
			httpHelper.setPostParam("appId", "WBTOM");
			httpHelper.setPostParam("req", "SFN");
			httpHelper.setPostParam("user", map.get("phoneNumber"));
			httpHelper.setPostParam("pass", map.get("password"));
			Log.d("DEBUG", "send friend pass: " + map.get("password"));
			ArrayList<String> friend = 
					DeviceHelper.getAllPhoneNumber(this.activity);
			
			
			
			for(int i = 0; i < friend.size(); i ++) {
				Log.d("DEBUG", "friend: " + friend.get(i));
				JsonHelper.getInstance().addFriend(friend.get(i));
			}
			String friends = JsonHelper.getInstance().getAllFriend();
//			friends = friends.substring(0, friends.length());
			httpHelper.setPostParam("friends",friends);
			Log.d("DEBUG", friends);
			
			
			
//			httpHelper.setPost(false);
//			httpHelper.setUrl(params[0]);
//			httpHelper.setGetParam("appId", "WBTOM");
//			httpHelper.setGetParam("req", "SFN");
//			httpHelper.setGetParam("user", map.get("phoneNumber"));
//			httpHelper.setGetParam("pass", map.get("password"));			
//			for(int i = 0; i < friend.size(); i ++) {
////				Log.d("DEBUG", "friend: " + friend.get(i));
//				JsonHelper.getInstance().addFriend(friend.get(i));
//			}
//			httpHelper.setGetParam("friends", 
//					JsonHelper.getInstance().getAllFriend());			
			
			httpHelper.sendRequest();
			this.setResponse(httpHelper.getResponse());
			Log.d("DEBUG","FRIEND RESPONSE==== "+this.getResponse());
			return this.getResponse();
		}
	}	
}
